<template>
  <gui-page
    ref="guiPage"
    :customHeader="true"
    :headerClass="['gui-bg-white', 'gui-dark-bg-level-1']"
  >
    <!-- 自定义头部导航 -->
    <template v-slot:gHeader>
      <view
        style="height: 44px; padding: 0 25rpx"
        class="gui-flex gui-nowrap gui-rows gui-align-items-center gui-bg-white gui-border-b"
      >
        <!-- 导航文本此处也可以是其他自定义内容 -->
        <view
          class="gui-h5 gui-blod search-container gui-justify-content-center align-items-center gui-ellipsis gui-primary-text"
        >
          <gui-search
            :focus="focus"
            @clear="searchStr = ''"
            @inputting="inputting"
            @confirm="confirm"
          ></gui-search>
        </view>
        <!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
        <!-- 实际宽度请根据自己情况设置 -->
        <view
          @click="goBack()"
          style="
            width: 120rpx;
            color: #303030;
            text-align: center;
            font-size: 28rpx;
          "
        >
          取消
        </view>
        <!-- 如果右侧有其他内容可以利用条件编译和定位来实现-->
      </view>

      <view v-show="isNotEmpty(searchStr)" style="height: calc(100vh - 88rpx)">
        <view style="padding: 0 25rpx">
          <view
            @tap="goNote(item.noteTitle)"
            v-for="item of searchList"
            hover-class="xhs-tap"
            class="gui-flex gui-rows gui-nowrap xhs-border-b"
            style="height: 50rpx; line-height: 50rpx; padding: 20rpx 10rpx"
          >
            <text
              class="gui-color-gray gui-icons small-text xhs-margin-right-20"
              >&#xe604;
            </text>
            <view
              class="gui-primary-text xhs-font28 gui-flex1"
              v-html="highlightText(item.noteTitle)"
            >
            </view>
            <text class="gui-color-gray gui-icons small-text">&#xe601;</text>
          </view>
        </view>
      </view>
    </template>
    <!-- 页面主体 -->
    <template v-slot:gBody>
      <view class="gui-padding gui-bg-white">
        <view class="gui-flex gui-rows gui-nowrap gui-align-items-center">
          <text class="xhs-font28 search-title">历史记录</text>
          <text class="gui-primary-text gui-h6 gui-flex1"></text>
          <!--<text @tap="clearHistory" class="gui-color-gray gui-icons small-text">&#xe794;</text>-->
        </view>

        <view class="search-history">
          <view
            class="history-item"
            @tap="goNote(item.content)"
            v-for="item of historyList"
          >
            {{ item.content }}
          </view>
        </view>

        <view
          class="gui-flex gui-rows gui-nowrap gui-margin-top gui-align-items-center"
        >
          <text class="xhs-font28 search-title">搜索发现</text>
          <text class="gui-primary-text gui-h6 gui-flex1"></text>
          <!--<text class="gui-color-gray gui-icons small-text">&#xe635;-->
          <!--</text>-->
        </view>

        <view class="xhs-font28" style="margin-top: 16rpx">
          <view class="gui-flex gui-row gui-wrap">
            <view
              class="gui-ellipsis search-hot"
              @tap="goNote(item.content)"
              v-for="item of hotHistoryList"
              style="width: 50%; height: 70rpx; color: #707070"
            >
              {{ item.content }}
              <image
                v-if="item.isHot"
                style="width: 24rpx; height: 24rpx"
                src="/static/search/hot@2x.png"
              ></image>
            </view>
          </view>
        </view>
      </view>

      <view
        class="gui-flex gui-padding-x gui-bg-white search-title"
        style="color: #ff6a00; font-weight: bold"
      >
        摇爪热门
      </view>
      <view
        class="gui-padding gui-flex gui-column gui-bg-white"
        style="flex: 1"
      >
        <template v-for="(item, index) of hotNoteList">
          <view
            @tap="goNote(item.noteTitle)"
            v-if="item.noteTitle && item.noteTitle.trim() !== ''"
            style="
              height: 60rpx;
              line-height: 60rpx;
              padding: 0 5rpx;
              color: #707070;
            "
          >
            <view
              class="xhs-font28 gui-ellipsis search-hot"
              style="width: 600rpx"
            >
              {{ item.noteTitle }}
              <image
                v-if="item.isHot"
                style="width: 24rpx; height: 24rpx"
                src="/static/search/hot@2x.png"
              ></image>
            </view>
          </view>
        </template>
      </view>
    </template>
  </gui-page>
</template>
<script>
import graceJS from "@/Grace6/js/grace.js";
import GuiImage from "../../Grace6/components/gui-image";
import GuiPage from "@/Grace6/components/gui-page.vue";
import commonMixin from "@/mixin/commonMinxin";
var demoData = [
  {
    img: "https://images.unsplash.com/photo-1662855802197-f2fe21494bf8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyNDJ8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80",
    title: "项目标题 01",
    checked: false,
  },
  {
    img: "https://images.unsplash.com/photo-1662855802197-f2fe21494bf8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyNDJ8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80",
    title: "项目标题 02",
    checked: true,
  },
  {
    img: "https://images.unsplash.com/photo-1662855802197-f2fe21494bf8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyNDJ8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80",
    title: "项目标题 03",
    checked: false,
  },
  {
    img: "https://images.unsplash.com/photo-1662855802197-f2fe21494bf8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyNDJ8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80",
    title: "项目标题 04",
    checked: false,
  },
];

export default {
  mixins: [commonMixin],
  components: {
    GuiPage,
    GuiImage,
  },
  data() {
    return {
      focus: false,
      lists: [],
      pageStyle: {},
      searchStr: "",
      searchList: [],
      historyList: [],
      hotHistoryList: [],
      hotNoteList: [],
      navType: null,
      accessToken: "",
      userId: "",
    };
  },
  onLoad(options) {
    this.accessToken = options.accessToken;
    this.userId = options.userId;
    this.navType = options.type;
    this.focus = false;
    // 模拟 api 请求
    setTimeout(() => {
      this.lists = demoData;
    }, 100);
    this.$nextTick(() => {
      setTimeout(() => {
        this.focus = true;
      }, 100);
    });
  },
  onShow() {
    this.getHistoryList();
    this.getHotHistoryList();
    this.getHotNoteList();
  },
  methods: {
    isNotEmpty(str) {
      return !uni.app.isEmpty(str);
    },
    goBack() {
      if (this.navType) {
        uni.navigateBack();
      } else {
        const platform = uni.getSystemInfoSync().platform;
        switch (platform) {
          case "android":
            // let ddd = {
            // 	hideNavBar: '1',
            // 	hideTotalNavBar: '1',
            // 	hideBottomSafeBar: '1',
            // 	url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/notes/detail/detail?noteId=${item.noteId}&token=${uni.getStorageSync("token")}&userId=${uni.getStorageSync("userId")}`
            // }
            // let d = JSON.stringify(ddd)
            // console.log(d, '都是对的')
            if (typeof window !== "undefined" && window.AndroidBridge) {
              window.AndroidBridge.backEvent();
            } else {
              uni.navigateBack();
            }
            console.log("运行Android上");
            break;
          case "ios":
            if (
              typeof window !== "undefined" &&
              window.webkit &&
              window.webkit.messageHandlers &&
              window.webkit.messageHandlers.backEvent
            ) {
              window.webkit.messageHandlers.backEvent.postMessage({});
            } else {
              uni.navigateBack();
            }
            break;
          default:
            console.log("运行在开发者工具上");
            uni.navigateBack();
            break;
        }
      }
    },
    highlightText(noteTitle) {
      if (this.searchStr) {
        const regex = new RegExp(this.searchStr, "gi");
        return noteTitle.replace(
          regex,
          (match) => `<text style="color:red;">${match}</text>`,
        );
      } else {
        return noteTitle;
      }
    },
    // 监听输入
    inputting: function (e) {
      console.log(e);
      this.searchStr = e;
      var mountedTimer = null;
      if (mountedTimer != null) {
        clearTimeout(mountedTimer);
      }
      mountedTimer = setTimeout(() => {
        this.getNotesLike(e);
      }, 200);
    },
    getNotesLike(noteTitle) {
      uni.app.post(
        "/blog/note/getVagueNotes",
        {
          limit: 10,
          offset: 1,
          noteTitle: noteTitle,
        },
        "",
        "",
        (res) => {
          this.searchList = res.data.records;
        },
      );
    },
    getHistoryList() {
      uni.app.post(
        "/blog/note/getHistory",
        {
          authorId: uni.getStorageSync("userId"),
        },
        "",
        "",
        (res) => {
          this.historyList = res.data;
        },
      );
    },
    getHotHistoryList() {
      uni.app.post(
        "/blog/note/getHotHistory",
        {
          authorId: uni.getStorageSync("userId"),
        },
        "",
        "",
        (res) => {
          // 过滤掉 content 为空或空字符串的项
          this.hotHistoryList = res.data.filter(
            (item) => item.content && item.content.trim() !== "",
          );
        },
      );
    },
    getHotNoteList() {
      uni.app.post(
        "/blog/note/getHotNotes",
        {
          authorId: uni.getStorageSync("userId"),
        },
        "",
        "",
        (res) => {
          this.hotNoteList = res.data;
        },
      );
    },
    clearHistory() {
      uni.showModal({
        title: "确定要全部删除吗?",
        success: (e) => {
          if (e.confirm) {
            uni.app.post(
              "/blog/note/deleteHistory",
              {
                authorId: uni.getStorageSync("userId"),
              },
              "",
              "",
              (res) => {
                this.historyList = res.data;
              },
            );
          }
        },
      });
    },
    confirm() {
      uni.navigateTo({
        url: `/pages/noteList/noteList?searchStr=${this.searchStr}&type=1&accessToken=${this.accessToken}&userId=${this.userId}`,
      });
    },
    goNote(e) {
      uni.navigateTo({
        url: `/pages/noteList/noteList?searchStr=${e}&type=1&accessToken=${this.accessToken}&userId=${this.userId}`,
      });
    },
  },
  mounted: function () {
    var mountedTimer = null;
    if (mountedTimer != null) {
      clearTimeout(mountedTimer);
    }
    mountedTimer = setTimeout(() => {
      // 01. 获取页面主体高度
      graceJS.getRefs("guiPage", this, 0, (ref) => {
        ref.getDomSize("guiPageBody", (e) => {
          console.log(e);
          this.pageStyle.height = e.height - uni.upx2px(88); //导航栏高度
        });
      });
    }, 100);
  },
};
</script>
<style lang="scss" scoped>
.search-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #303030;
}
.search-history {
  margin-top: 32rpx;
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
  .history-item {
    display: flex;
    align-items: center;
    height: 40rpx;
    text-align: center;
    padding: 0 24rpx;
    line-height: 40rpx;
    border-radius: 40rpx;
    border: 1px solid #707070;
    font-size: 26rpx;
    color: #707070;
  }
}
.search-hot {
  display: flex;
  gap: 16rpx;
  align-items: center;
}
/* #ifdef MP  */
.search-container {
  padding-top: 40rpx;
  width: 350rpx !important;
}

/* #endif */

/* #ifdef H5 */
.search-container {
  flex: 1 !important;
}

/* #endif */
</style>
